import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/quiz/BGQuizController.dart';
import 'package:ichinesereader/exam/util/ExamLayoutUtil.dart';
import 'package:ichinesereader/exam/util/ExamUtil.dart';
import 'package:ichinesereader/exam/widgets/BGExamSectionWidget.dart';
import 'package:ichinesereader/exam/widgets/BGExamWidget.dart';
import 'package:ichinesereader/exam/widgets/SampleAudioPlayer.dart';
import 'package:ichinesereader/utils/StrUtil.dart';

import 'BGQuizIndexPage.dart';

class BGQuizPage extends GetView<BGQuizController> {
  BGQuizPage({required this.assessmentId, required this.username, this.isOnePage = false, Key? key}) : super(key: key);
  final String assessmentId;
  final String username;
  final bool isOnePage;

  @override
  Widget build(BuildContext context) {
    MediaQuery.of(context).size.width;
    if (StrUtil.hasValue(assessmentId) && !controller.isLoad.value) {
      controller.assessmentId = assessmentId;
      controller.username = username;
      controller.loadData(assessmentId);
    }
    return Scaffold(
        appBar: AppBar(title: Text('Quiz'), centerTitle: true, actions: [
          TextButton(
              onPressed: () async {
                showGeneralDialog(
                    context: Get.context!,
                    transitionDuration: const Duration(milliseconds: 400),
                    pageBuilder: (bc, ania, anis) {
                      return BGQuizIndexPage(
                          indexList: controller.indexList,
                          undoneNumList: controller.verifyCompleteAllQuestion(),
                          getIndex: (section, index) {
                            if (!controller.isLoad.value) return;
                            if (isOnePage) {
                              controller.scrollToIndex(section, index);
                            } else {
                              controller.currentIndex.value = controller.sectionIndexMap[section]![index]!;
                              controller.getCurrentSection();
                            }
                          });
                    });
              },
              child: const Text('INDEX', style: TextStyle(color: Colors.white70, fontSize: 20))),
          SizedBox(width: 10),
          IconButton(
              icon: Icon(Icons.save, color: Color(0xFF212529)),
              tooltip: 'Save',
              onPressed: () {
                if (!controller.isLoad.value) return;
                controller.reportRecord();
                Future.delayed(const Duration(milliseconds: 500), () {
                  Get.snackbar('Message'.tr, 'Saved Successfully'.tr, snackPosition: SnackPosition.TOP);
                });
              }),
          SizedBox(width: 10),
          IconButton(
              icon: Icon(Icons.upload, color: Color(0xFF212529)),
              tooltip: 'Submit',
              onPressed: () {
                if (!controller.isLoad.value) return;
                List numList = controller.verifyCompleteAllQuestion();
                showQuestionDialog(Get.context!, numList);
              }),
          SizedBox(width: 10)
        ]),
        body: Obx(() => isOnePage ? _buildOnePageExam() : _buildPagesExam()));
  }

  Widget _buildContentWidget() {
    QuestionContent content = controller.allSectionContent[controller.currentSection.value];
    List<Widget> options = [];
    if (content.show != null) {
      if (content.audio != null) {
        content.json = content.audio;
        content.audio = null;
      }
      String audioUrl = content.json ?? '';
      options.add(Padding(padding: EdgeInsets.only(bottom: 15), child: ExamUtil.buildHeadInfoWidget(content, Get.context!)));
      if (audioUrl != '') {
        options.add(SampleAudioPlayer(name: 'audioPlayerExam', audioUrl: audioUrl));
        options.add(SizedBox(height: 15));
      }
      options.add(Container(padding: const EdgeInsets.only(bottom: 15), child: const Divider(height: 2, color: Colors.grey)));
    }
    return Column(children: options);
  }

  Widget _buildPagesExam() {
    if (!controller.isLoad.value) return SizedBox();
    int currentIndex = controller.currentIndex.value;
    return Container(
        padding: EdgeInsets.all(20),
        child: Column(children: [
          Expanded(
              child: Container(
                  decoration: ExamLayoutUtil.getBoxDecoration(),
                  width: double.infinity,
                  child: Container(
                      padding: const EdgeInsets.all(20),
                      child: Scrollbar(
                          thumbVisibility: true,
                          child: SingleChildScrollView(
                              primary: true,
                              child: Column(children: [
                                Obx(() => _buildContentWidget()),
                                Obx(() => BGExamWidget(questionItem: controller.allItems[controller.currentIndex.value]))
                              ])))))),
          Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: Obx(() => Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                    ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          textStyle: TextStyle(fontSize: 20, fontFamily: 'Montserrat', letterSpacing: 0.2, fontWeight: FontWeight.bold),
                          padding: EdgeInsets.symmetric(horizontal: 42, vertical: GetPlatform.isWeb ? 20 : 12),
                          backgroundColor: Get.isDarkMode ? Colors.white54 : Color(0xFF35A95D),
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          elevation: 10,
                        ),
                        onPressed: () {
                          if (currentIndex == 0) {
                            Get.back();
                          } else {
                            controller.prevPage();
                          }
                        },
                        child: Text((currentIndex == 0) ? 'BACK' : 'PREV')),
                    ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          textStyle: TextStyle(fontSize: 20, fontFamily: 'Montserrat', letterSpacing: 0.2, fontWeight: FontWeight.bold),
                          padding: EdgeInsets.symmetric(horizontal: 26, vertical: GetPlatform.isWeb ? 20 : 12),
                          backgroundColor: Get.isDarkMode ? Colors.white54 : Color(0xFF35A95D),
                          foregroundColor: Get.isDarkMode ? Colors.black54 : Colors.white,
                          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                          elevation: 15,
                        ),
                        onPressed: () {
                          if (currentIndex < controller.allItems.length - 1) {
                            controller.nextPage();
                          } else {
                            List numList = controller.verifyCompleteAllQuestion();
                            showQuestionDialog(Get.context!, numList);
                          }
                        },
                        child: Text(controller.currentIndex.value < controller.allItems.length - 1 ? '   NEXT  ' : 'SUBMIT'))
                  ])))
        ]));
  }

  Widget _buildOnePageExam() {
    List<Widget> options = [];
    if (controller.isLoad.value) {
      for (int i = 0; i < controller.assessmentResult!.list!.length; i++) {
        QuestionPart? part = controller.assessmentResult!.list?[i];
        for (int j = 0; j < part!.questions!.length; j++) {
          QuestionSection section = part.questions![j];
          int sectionNum = 0;
          if (i > 0) {
            sectionNum = i;
          } else {
            if (j > 0) sectionNum = j;
          }
          options.add(Container(
              margin: EdgeInsets.only(top: 20),
              padding: EdgeInsets.fromLTRB(10, 20, 10, 20),
              decoration: ExamLayoutUtil.getBoxDecoration(),
              child: BGExamSectionWidget(questionSection: section, isRecordSmall: true, keyList: controller.keyList[sectionNum])));
        }
      }
      options.add(SizedBox(height: 50));
    }
    return Scrollbar(
        thickness: 10,
        thumbVisibility: true,
        controller: controller.scrollCrl,
        child: SingleChildScrollView(
            controller: controller.scrollCrl, child: Padding(padding: EdgeInsets.only(left: 10, right: 10), child: Column(children: options))));
  }

  void showQuestionDialog(BuildContext context, List list) async {
    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
            title: Text('Are you sure you want to submit?',
                textAlign: TextAlign.center, style: TextStyle(color: Color(0xff3d6f8c), fontSize: 22, fontWeight: FontWeight.w500)),
            content: SizedBox(
                width: 350,
                height: list.isEmpty ? 10 : 200,
                child: list.isEmpty
                    ? SizedBox()
                    : Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                        Text('Undone Index:', style: TextStyle(color: Get.isDarkMode ? Colors.white : Colors.red, fontSize: 18)),
                        SizedBox(height: 10),
                        Expanded(
                            child: Scrollbar(
                                thumbVisibility: true,
                                child: SingleChildScrollView(
                                    primary: true,
                                    child: Text(list.toString(),
                                        style: TextStyle(color: Get.isDarkMode ? Colors.white60 : Color(0xFF212529), fontSize: 16, height: 1.5)))))
                      ])),
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0))),
            contentPadding: const EdgeInsets.fromLTRB(24, 15, 24, 30),
            actions: <Widget>[
              TextButton(
                  child: Text('Cancel', style: TextStyle(color: Colors.grey, fontSize: 16)),
                  onPressed: () {
                    Get.back();
                  }),
              TextButton(
                  child: Text('Submit', style: TextStyle(fontSize: 16)),
                  onPressed: () {
                    Get.back();
                    controller.submitAction();
                  })
            ]);
      },
    );
  }
}
